package ziqiangwanqiang.com.boss.channel

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.content.pm.ResolveInfo
import android.net.Uri
import android.os.Build
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import ziqiangwanqiang.com.InstallFileProvider
import java.io.File

class Install : MethodChannel.MethodCallHandler {
    var context: Context
    var activity: Activity
    var flutterEngine: FlutterEngine
    var methodChannel: MethodChannel
    var methodChannelName: String = "com.ziqiangwanqiang.install"

    constructor(context: Context, activity: Activity, flutterEngine: FlutterEngine) {
        this.context = context
        this.activity = activity
        this.flutterEngine = flutterEngine

        methodChannel = MethodChannel(flutterEngine.dartExecutor.binaryMessenger, methodChannelName)
        methodChannel.setMethodCallHandler(this)
    }

    override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) {
        if (call.method.equals("install")) {
            install(call, result)
        } else {
            result.notImplemented()
        }
    }

    private fun install(call: MethodCall, result: MethodChannel.Result) {
        var filePath: String? = call.argument<String>("filePath")

        var file: File = File(filePath)

        if (!file.exists()) {
            result.error("file not exists", "file not exists", null)
            return
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            install24(file)
        } else {
            installBelow24(file)
        }
    }

    private fun installBelow24(file: File) {
        val intent = Intent(Intent.ACTION_VIEW)
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
        val uri = Uri.fromFile(file)
        intent.setDataAndType(uri, "application/vnd.android.package-archive")
        context.startActivity(intent)
    }

    private fun install24(file: File) {
        val uri: Uri = InstallFileProvider.getUriForFile(context, "ziqiangwanqiang.com.boss.fileProvider.install", file)
        val intent = Intent(Intent.ACTION_VIEW)
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
        intent.setDataAndType(uri, "application/vnd.android.package-archive")

        val resInfoList: List<ResolveInfo> = activity.packageManager.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY)
        for (resolveInfo in resInfoList) {
            val packageName = resolveInfo.activityInfo.packageName
            activity.grantUriPermission(packageName, uri, Intent.FLAG_GRANT_WRITE_URI_PERMISSION or Intent.FLAG_GRANT_READ_URI_PERMISSION)
        }
        context.startActivity(intent)
    }
}